<template>
    <div style="display: flex; align-items: center">
        <div class="index" :style="{ width: showPDF ? '60vw' : '100vw' }">
            <!-- 登录/注册或个人中心按钮 -->
            <indexUser></indexUser>
            <!-- 聊天记录展示框 -->
            <div class="conversationContent" v-if="haveSend">
                <el-scrollbar ref="scrollbar" height="60vh" always>
                    <!-- 历史聊天记录 -->
                    <div v-if="historyArray.length > 0">
                        <div class="histroyContent" v-for="(item, index) in historyArray" :key="index">
                            <!-- 用户问题 -->
                            <div class="userSend" v-show="item.role == 'user'">
                                <div class="userMsg">
                                    {{ item.content }}
                                </div>
                                <div class="userImg">
                                    <img src="@/assets/user 2.png" alt="" />
                                </div>
                            </div>
                            <!-- ai回答 -->
                            <div class="aiSend" v-show="item.role == 'ai'">
                                <div class="aiImg">
                                    <img src="@/assets/robot.png" alt="" />
                                </div>
                                <!-- ai推理块 -->
                                <div class="aiReason">
                                    {{ item.reason }}
                                </div>
                                <!-- ai回答内容 -->
                                <div class="aiContent markdown-body" v-html="md.render(item.content)"></div>
                                <!-- echarts图表 -->
                                <div class="echarts" style="width: 400px; height: 400px; margin: 0 auto"
                                    v-if="JSON.stringify(item.echarts) !== '{}'">
                                    <v-chart autoresize :option="item.echarts"
                                        style="height: 100%; width: 100%"></v-chart>
                                </div>
                                <!-- 引用文件列表 -->
                                <div class="aiFile" v-show="item.role === 'ai' && (item.file || []).length > 0">
                                    <div class="line"></div>
                                    <div v-for="(file, index) in item.file" :key="index" class="aiFileContent">
                                        <div class="aiFileName" @click="toPDF(file.fileURL, file.fileName)">
                                            <i class="iconfont icon-PDF" style="color: red"></i>
                                            {{ file.fileName }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="aiText" style="text-align: right; color: #b4a9a7; font-size: 12px"
                                v-show="item.role == 'ai'">
                                内容AI生成，仅供参考，不构成医疗建议
                            </div>
                        </div>
                    </div>
                    <!-- 发送消息的问答对 -->
                    <div class="sendContent" v-if="isLoading">
                        <!-- 用户问题 -->
                        <div class="userSend">
                            <div class="userMsg">
                                {{ userMsg }}
                            </div>
                            <div class="userImg">
                                <img src="@/assets/user 2.png" alt="" />
                            </div>
                        </div>
                        <!-- ai回答 -->
                        <div class="aiSend">
                            <div class="aiImg">
                                <img src="@/assets/robot.png" alt="" />
                            </div>
                            <!-- ai推理模块 -->
                            <div class="aiReason" v-if="aiReasonMsg" v-html="md.render(aiReasonMsg)"></div>
                            <!-- ai回答模块 -->
                            <div class="aiContent markdown-body" v-if="aiMsg" v-html="md.render(aiMsg)"></div>
                            <!-- 正在加载 -->
                            <div class="aiLoading" v-if="!aiReasonMsg && !aiMsg">
                                <div class="aiLoadingText">{{ loadingText }}</div>
                                <Loading></Loading>
                            </div>
                        </div>
                    </div>
                    <!-- 添加一个底部占位元素，用于滚动定位 -->
                    <div ref="bottomElement"></div>
                </el-scrollbar>
            </div>
            <!-- 中心输入框 -->
            <div class="center" :style="{ margin: haveSend ? '0 auto' : '15vh auto 5vh' }">
                <div class="centerLogo" v-if="!haveSend">
                    <img src="../../assets/logo.png" alt="" />
                </div>
                <div class="content" :style="{
                    margin: haveSend ? '3vh auto' : '6vh auto',
                    paddingTop: fileUploadFlag ? '10px' : '30px',
                }">
                    <!-- 数据分析展示文件 -->
                    <div class="fileBox" v-if="fileUploadFlag">
                        <div class="fileImg">
                            <img :src="fileInfoData.img" alt="" />
                        </div>
                        <div class="fileInfo">
                            <div class="fileName">
                                {{ fileInfoData.name }}
                            </div>
                            <div class="fileSize">
                                {{ fileInfoData.size }}
                            </div>
                        </div>
                    </div>
                    <div class="sendInput">
                        <!-- 普通问答 数据分析 -->
                        <el-input v-model="message" style="width: 40vw" placeholder="我是先锋小科，为您提供实用的建议和帮助，让我们开始交流吧！"
                            autosize clearable type="textarea" @keyup.enter="sendMsg" v-if="!knowledge" />
                        <!-- 选择知识库文件 -->
                        <el-mention v-model="mentionValue" :options="options" type="textarea" style="width: 40vw" whole
                            :check-is-whole="checkIsWhole" placement="top" placeholder="我是先锋小科，为您提供实用的建议和帮助，让我们开始交流吧！"
                            v-if="knowledge" @keyup.enter="sendMsg">
                            <template #header>
                                <div class="mentionTitle">
                                    <i class="icon-Altgo_ iconfont"></i>
                                    选择知识库文件
                                </div>
                            </template>
                            <template #label="{ item }">
                                <div style="display: flex; align-items: center">
                                    <i class="icon-PDF iconfont" style="display: inline-block; color: red"></i>
                                    <span style="margin-left: 6px">{{ item.value }}</span>
                                </div>
                            </template>
                        </el-mention>
                    </div>
                    <div class="functionBtn" :style="{ marginTop: fileUploadFlag ? '0px' : '40px' }">
                        <div class="btnLeft">
                            <div class="knowledge" @click="useKnowledge"
                                :class="knowledge ? 'useKnowledge' : 'noKnowledge'">
                                <div class="knowledgeText" :class="knowledge ? 'useKnowledgeText' : 'noKnowledgeText'">
                                    启用知识库
                                </div>
                            </div>
                            <div class="think" @click="deepThink" :class="think ? 'deepThink' : 'noDeepThink'">
                                <div class="iconfont icon-a-Group2147227608"
                                    :class="think ? 'deepThinkText' : 'noDeepThinkText'"></div>
                                <div class="thinkText" :class="think ? 'deepThinkText' : 'noDeepThinkText'">
                                    深度推理
                                </div>
                            </div>
                        </div>
                        <div class="btnRight">
                            <div class="at">
                                <el-upload class="upload" :http-request="handleKnowledgeUpload"
                                    :show-file-list="false" :disabled="!getToken()"
                                    accept=".pdf,.doc,.docx,.txt,.md,.csv">
                                    <i class="iconfont icon-Altgo_"></i>
                                </el-upload>
                            </div>
                            <div class="link">
                                <el-upload class="upload" :http-request="handleKnowledgeUpload"
                                    :show-file-list="false" :disabled="!getToken()"
                                    accept=".pdf,.doc,.docx,.txt,.md,.csv">
                                    <i class="iconfont icon-lianjie"></i>
                                </el-upload>
                            </div>
                            <div class="send" @click="sendMsg">
                                <img src="../../assets/send.png" alt="" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 工具栏按钮 -->
            <ToolNav v-show="getToken()"></ToolNav>

            <!-- 词条 -->
            <div class="entryOne" v-if="!haveSend">
                <div class="entryItem" @click="sendMsg(0)">
                    {{ randomQuestion[0] }}
                </div>
                <div class="entryItem" @click="sendMsg(1)">
                    {{ randomQuestion[1] }}
                </div>
            </div>
            <div class="entryOne" style="margin-top: 30px" v-if="!haveSend">
                <div class="entryItem" @click="sendMsg(2)">
                    {{ randomQuestion[2] }}
                </div>
                <div class="entryItem" @click="sendMsg(3)">
                    {{ randomQuestion[3] }}
                </div>
                <div class="entryItem" @click="sendMsg(4)">
                    {{ randomQuestion[4] }}
                </div>
            </div>
            <!-- 抽屉-历史聊天记录 -->
            <div class="drawer" :class="{ active: showDrawer }">
                <indexDrawer></indexDrawer>
            </div>
        </div>
        <div class="pdfContainer" v-if="showPDF">
            <indexPDF :pdfUrl="pdfURL" :pdfName="pdfName"></indexPDF>
        </div>
    </div>
</template>

<script setup>
import {
    ref,
    provide,
    reactive,
    nextTick,
    onMounted,
    onBeforeMount,
    onUnmounted,
    watch,
} from "vue";
import "@/markdown.css";
import MarkdownIt from "markdown-it";
import { getToken } from "../../utils/setToken";
import { ElMessage } from "element-plus";
import {
    chatAi,
    getConversationContent,
    createConversation,
} from "../../api/api/chat";
import {
    fetchDefaultKnowledgeBase,
    fetchKnowledgeBases,
    fetchKnowledgeDocuments,
    uploadKnowledgeDocument
} from "@/api/api/knowledge.js";
import { SetID } from "../../store/setID";
import ToolNav from "../../components/ToolNav.vue";
import indexUser from "./components/indexUser.vue";
import indexDrawer from "./components/indexDrawer.vue";
import indexPDF from "./components/indexPDF.vue";
import Loading from "../../components/Loading.vue";
import csv from "@/assets/csv.png";
import * as echarts from "echarts";
import chinaGeoJSON from "@/assets/china.json";
//实例化pinia
const SetIDStore = SetID();
//markdown转html
const md = new MarkdownIt({
    html: true, // 启用HTML标签
    linkify: true, // 自动转换链接
    breaks: true, // 将单个换行符转换为 <br>
    typographer: true, // 启用智能引号等
});
echarts.registerMap("china", chinaGeoJSON);
//全局变量
const message = ref(""); //输入框的值
const think = ref(false); //是否深度推理
const knowledge = ref(false); //是否启用自己的知识库
const scrollbar = ref(null); //滚动框
const bottomElement = ref(null); //底部元素引用
const showDrawer = ref(false); //是否展示抽屉--历史记录
const newChat = ref(false); //是否开启新对话
const haveSend = ref(false); //是否发送了消息--控制是展示初始界面还是展示历史聊天记录，默认是展示初始界面
const userMsg = ref(""); //发送消息的问答对-用户信息
const aiReasonMsg = ref(""); //发送消息的问答对-ai信息-推理块
const aiMsg = ref(""); //发送消息的问答对-ai信息-回答块
const aiAnswerComplete = ref(true); //ai回答是否完毕-初始为true，第一次发送消息后改为false，防止重复发送
const isLoading = ref(false); //ai是否在思考--发送消息后显示ai正在思考，当有返回时，改为false，显示返回内容
const formData = reactive({
    conversation_id: null,
    content: "",
    knowledge_base_id: null,
    is_reasoning: false,
}); //对话传递的数据对象
const activeKnowledgeBaseId = ref(null); // 当前使用的知识库
const knowledgeBaseList = reactive([]); // 知识库列表
const conversationID = ref(0)
const historyArray = reactive([]); //历史记录数组
const isUserScrolling = ref(false); //用户是否正在手动滚动
const scrollTimer = ref(null); //滚动定时器
const fileUploadFlag = ref(false); //文件上传成功--显示文件列表
const fileInfoData = reactive({}); //上传文件的信息
const showPDF = ref(false); //展示pdf
const pdfURL = ref(); //传递pdf的url
const pdfName = ref(); //传递pdf的名称
const randomQuestion = reactive([]); //随机问题数组
const mentionValue = ref(""); //@提示框的值
const knowledgeArray = reactive([]); //用户知识库文件
const options = reactive([]);//知识库文件选项
const isMentionActive = ref(false)
const loadingText = ref('正在回答，请稍后')

const formatFileSize = (size) => {
    const MB = 1024 * 1024;
    const KB = 1024;
    if (size === 0) return "0 KB";
    if (!size) return "";
    return size >= MB
        ? `${(size / MB).toFixed(2)} MB`
        : `${(size / KB).toFixed(2)} KB`;
};

const normalizeListData = (payload) => {
    if (Array.isArray(payload)) return payload;
    if (Array.isArray(payload?.results)) return payload.results;
    if (Array.isArray(payload?.data)) return payload.data;
    return [];
};

const syncKnowledgeOptionsFromDocs = (docs = []) => {
    knowledgeArray.splice(0, knowledgeArray.length);
    options.splice(0, options.length);
    docs.forEach((item) => {
        const name = item.title || item.name || item.file_name || `文档-${item.id}`;
        const kbId = item.knowledge_base_id || item.knowledge_base || activeKnowledgeBaseId.value;
        knowledgeArray.push({
            id: item.id,
            name,
            kbId,
        });
        options.push({
            id: item.id,
            value: name,
        });
    });
};

const loadKnowledgeBases = async () => {
    if (!getToken()) return;
    try {
        const [defaultBase, baseListRes] = await Promise.all([
            fetchDefaultKnowledgeBase().catch(() => null),
            fetchKnowledgeBases().catch(() => []),
        ]);
        const bases = normalizeListData(baseListRes);
        knowledgeBaseList.splice(0, knowledgeBaseList.length, ...bases);
        if (defaultBase?.id) {
            activeKnowledgeBaseId.value = defaultBase.id;
        } else if (defaultBase?.knowledge_base?.id) {
            activeKnowledgeBaseId.value = defaultBase.knowledge_base.id;
        } else if (!activeKnowledgeBaseId.value && bases.length > 0) {
            activeKnowledgeBaseId.value = bases[0].id;
        }
    } catch (error) {
        console.error("加载知识库失败", error);
    }
};

const loadKnowledgeDocuments = async () => {
    if (!getToken()) return;
    try {
        const params = activeKnowledgeBaseId.value ? { knowledge_base_id: activeKnowledgeBaseId.value } : {};
        const res = await fetchKnowledgeDocuments(params);
        const docs = normalizeListData(res);
        syncKnowledgeOptionsFromDocs(docs);
    } catch (error) {
        console.error("获取知识库文件失败", error);
    }
};

const ensureKnowledgeBaseId = async () => {
    if (!activeKnowledgeBaseId.value) {
        await loadKnowledgeBases();
    }
    return activeKnowledgeBaseId.value;
};

// 知识库文件上传
const handleKnowledgeUpload = async (options) => {
    const { file, onSuccess, onError } = options;
    try {
        const kbId = await ensureKnowledgeBaseId();
        if (!kbId) {
            throw new Error("暂无可用知识库，请先创建知识库");
        }
        const form = new FormData();
        form.append("file", file);
        form.append("knowledge_base_id", kbId);
        form.append("title", file.name);

        const res = await uploadKnowledgeDocument(form);

        // 更新上传文件展示信息
        fileUploadFlag.value = true;
        fileInfoData.name = file.name;
        fileInfoData.size = formatFileSize(file.size);
        fileInfoData.img = csv;
        formData.knowledge_base_id = kbId;

        await loadKnowledgeDocuments();
        ElMessage({
            type: "success",
            message: "上传知识库成功！",
            duration: 1500,
        });
        onSuccess && onSuccess(res);
    } catch (err) {
        console.error(err);
        const errMsg = err?.message || "上传知识库失败，请重试！";
        ElMessage({
            type: "error",
            message: errMsg,
            duration: 1500,
        });
        onError && onError(err);
    }
};
//开启新对话-与子组件通信
provide("newChat", newChat);
watch(
    () => newChat.value,
    (newValue) => {
        if (newValue) {
            //清空聊天记录框
            historyArray.length = 0;
            newChat.value = false;
        }
    }
);
provide("showPDF", showPDF);
//展示pdf
const toPDF = (fileURL, fileName) => {
    pdfURL.value = "/api" + fileURL;
    pdfName.value = fileName;
    showPDF.value = true;
};

//当退格键被按下做删除操作时，检查是否将提及部分作为整体删除--与whole配合使用
const checkIsWhole = (pattern, prefix) => {
    return options.some(item => item.value === pattern);
};

//获取历史记录
const getHistory = () => {
    if (SetIDStore.C_ID == 0) {
        return;
    }
    getConversationContent(SetIDStore.getID())
        .then((res) => {
            //清空历史记录数组
            historyArray.length = 0;
            console.log('对话详情:', res);

            const messages = res?.messages || res?.data?.messages || [];

            if (Array.isArray(messages) && messages.length > 0) {
                messages.forEach((msg) => {
                    if (msg.role === 'user') {
                        const user = {
                            role: "user",
                            content: msg.content,
                        };
                        historyArray.push(user);
                    } else if (msg.role === 'assistant' || msg.role === 'ai') {
                        const ai = {
                            role: "ai",
                            reason: "",
                            content: msg.content,
                            questionID: msg.id,
                            echarts: {},
                            file: msg.retrieved_docs || msg.references || [],
                        };
                        historyArray.push(ai);
                    }
                });
            }

            console.log('处理后的历史记录:', historyArray);
            // 在历史记录加载完成后，滚动到底部
            nextTick(() => {
                scrollToBottom();
            });
        })
        .catch((err) => {
            console.error('获取历史记录失败:', err);
        });
};
//切换会话-显示聊天记录
watch(
    () => SetIDStore.C_ID,
    (newValue, oldValue) => {
        console.log('watch', newValue, oldValue)
        if (newValue && newValue != oldValue) {
            haveSend.value = true;
            aiAnswerComplete.value = true;
            isLoading.value = false;
            getHistory();
        }
    }
);
//自动滚动的函数
const scrollToBottom = () => {
    // 如果用户正在手动滚动，不要干扰
    if (isUserScrolling.value) return;

    // 使用 requestAnimationFrame 确保在下一帧渲染前执行
    requestAnimationFrame(() => {
        if (bottomElement.value) {
            bottomElement.value.scrollIntoView({ behavior: "smooth", block: "end" });
        } else if (scrollbar.value) {
            try {
                const scrollContainer = scrollbar.value.wrap;
                if (scrollContainer) {
                    const targetPosition = scrollContainer.scrollHeight;
                    scrollContainer.scrollTop = targetPosition;
                }
            } catch (error) {
                console.error("滚动错误:", error);
            }
        }
    });
};

// 监听滚动事件
const handleScroll = () => {
    // 用户开始滚动
    isUserScrolling.value = true;

    // 清除之前的定时器
    if (scrollTimer.value) {
        clearTimeout(scrollTimer.value);
    }

    // 设置新的定时器，用户停止滚动1秒后重置标志
    scrollTimer.value = setTimeout(() => {
        isUserScrolling.value = false;
    }, 1000);
};


const createNewConversationIfNeeded = async (title) => {
    if (formData.conversation_id) return formData.conversation_id;
    try {
        const res = await createConversation({ title: title?.slice(0, 30) || "新会话" });
        const cid = res?.id || res?.conversation_id;
        if (cid) {
            formData.conversation_id = cid;
            SetIDStore.setID(cid);
            return cid;
        }
    } catch (error) {
        console.error("创建会话失败", error);
    }
    return null;
};

//发送消息函数
const sendMsg = async (index) => {
    //若是知识问答模式--匹配文件名以及用户问的内容
    if (knowledge.value) {
        const mentionedNames = [
            ...mentionValue.value.matchAll(/@([^\s@]+)/g),
        ].map((match) => match[1]);

        const plainText = mentionValue.value
            .replace(/@[^\s@]+/g, "")
            .trim();

        //若内容匹配到的是空字符，则不会继续往下执行
        if (!plainText) return;

        message.value = plainText;

        const nameToDocMap = knowledgeArray.reduce((map, item) => {
            map[item.name] = item;
            return map;
        }, {});

        const matchedDocs = mentionedNames
            .map((name) => nameToDocMap[name])
            .filter(Boolean);

        if (matchedDocs.length > 0) {
            const kbIdFromDocs = matchedDocs.find((doc) => doc.kbId)?.kbId;
            formData.knowledge_base_id = kbIdFromDocs || activeKnowledgeBaseId.value;
        } else {
            formData.knowledge_base_id = activeKnowledgeBaseId.value;
        }

        mentionValue.value = "";
    }
    //是否传递了参数
    if (typeof index == "number") {
        message.value = randomQuestion[index];
    }
    //去除收尾空格
    message.value = message.value.trim()

    //发送消息不能为空
    if (!message.value) {
        ElMessage({
            type: "error",
            message: "发送消息不能为空!",
            duration: 1500,
        });
        return;
    }

    //ai回答完毕之前不能重复发送
    if (!aiAnswerComplete.value) {
        ElMessage({
            type: "error",
            message: "正在回答，请稍候！",
            duration: 1500,
        });
        return;
    }

    //展示ai思考
    isLoading.value = true;
    loadingText.value = "正在回答，请稍后";

    //ai正在回答-改为false
    aiAnswerComplete.value = false;

    //赋值给发送消息问答对-用户信息
    userMsg.value = message.value;

    //清空对话框
    message.value = "";

    //展示历史聊天记录
    haveSend.value = true;

    if (SetIDStore.C_ID != 0) {
        formData.conversation_id = SetIDStore.C_ID;
    }
    formData.content = userMsg.value;

    // 普通问答不强制绑定知识库
    if (!knowledge.value) {
        formData.knowledge_base_id = null;
    }

    // 重置用户滚动标志，确保新消息时可以自动滚动
    isUserScrolling.value = false;

    // 清空之前的内容
    aiReasonMsg.value = "";
    aiMsg.value = "";

    // 发送消息后立即滚动到底部
    nextTick(() => {
        scrollToBottom();
    });

    // 仅在知识库问答时确保知识库 ID
    if (knowledge.value) {
        if (!formData.knowledge_base_id) {
            formData.knowledge_base_id = await ensureKnowledgeBaseId();
        }
        if (!formData.knowledge_base_id) {
            ElMessage.error("暂无可用知识库，请先在个人中心创建知识库");
            aiAnswerComplete.value = true;
            isLoading.value = false;
            return;
        }
    }

    // 确保会话 ID
    if (!formData.conversation_id) {
        const cid = await createNewConversationIfNeeded(userMsg.value);
        if (!cid) {
            ElMessage.error("创建会话失败，请重试");
            aiAnswerComplete.value = true;
            isLoading.value = false;
            return;
        }
    }

    const useRag = knowledge.value && !!formData.knowledge_base_id;
    const requestData = {
        question: formData.content,
        conversation_id: formData.conversation_id || null,
        knowledge_base_id: useRag ? formData.knowledge_base_id : null,
        use_rag: useRag,
        ...(useRag ? { top_k: 3 } : {}),
    };

    chatAi(requestData)
        .then((res) => {
            //关闭文件展示
            fileUploadFlag.value = false;

            // 设置会话ID
            const currentConversationId = res.conversation_id || res?.conversation?.id || formData.conversation_id;
            if (currentConversationId) {
                conversationID.value = currentConversationId;
                formData.conversation_id = currentConversationId;
                SetIDStore.setID(currentConversationId);
            }

            // 设置AI回答
            const answerText =
                res.answer ||
                res.content ||
                res.response ||
                res?.data?.answer ||
                res?.data?.content ||
                res?.data?.response ||
                res?.result ||
                res?.data?.result ||
                "";
            aiMsg.value = answerText;

            // 结束加载状态
            aiAnswerComplete.value = true;
            isLoading.value = false;

            // 保存当前问答对到历史数组
            const userEntry = {
                role: "user",
                content: userMsg.value,
            };
            const aiEntry = {
                role: "ai",
                reason: "",
                content: aiMsg.value,
                file:
                    res.retrieved_docs ||
                    res.references ||
                    res?.data?.retrieved_docs ||
                    res?.data?.references ||
                    []
            };
            historyArray.push(userEntry, aiEntry);

            // 滚动到底部
            nextTick(() => {
                scrollToBottom();
            });
        })
        .catch((err) => {
            console.error('发送消息失败:', err);
            const msg = err?.message || "";
            // 若已由全局拦截器提示超时/未登录等，这里避免重复弹窗
            if (!/超时|timeout/i.test(msg)) {
                ElMessage.error('发送失败，请重试！');
            }
            aiAnswerComplete.value = true;
            isLoading.value = false;
            loadingText.value = /超时|timeout/i.test(msg)
                ? '请求超时，请稍后重试！'
                : '发送失败，请重试！';
        });
    watch(() => aiMsg.value, (newValue) => {
        aiMsg.value = newValue.replace(/\\n/g, "\n")
    })
};

//获取用户知识库文件
const getUserKonwledgeFile = async () => {
    if (!getToken()) return;
    await loadKnowledgeBases();
    await loadKnowledgeDocuments();
}

onBeforeMount(() => {
    // 初始化随机问题
    randomQuestion.push(
        "什么是Python中的装饰器？",
        "如何学习Django框架？",
        "什么是RESTful API？",
        "如何优化数据库查询？",
        "前端性能优化有哪些方法？"
    );
    getUserKonwledgeFile()
});

// 组件挂载后初始化--添加滚动事件
onMounted(() => {
    // 添加滚动事件监听
    if (scrollbar.value && scrollbar.value.wrap) {
        scrollbar.value.wrap.addEventListener("scroll", handleScroll);
    }

    // 确保滚动容器正确初始化
    nextTick(() => {
        if (haveSend.value) {
            scrollToBottom();
        }
    });
});

//切换深度推理
const deepThink = () => {
    //开启深度推理
    think.value = !think.value;
    if (think.value) {
        ElMessage({
            type: "success",
            message: "已开启深度推理",
            duration: 1500,
        });
        formData.is_reasoning = true;
    } else {
        ElMessage({
            type: "success",
            message: "已关闭深度推理",
            duration: 1500,
        });
        formData.is_reasoning = false;
    }
};

//切换知识库
const useKnowledge = () => {
    //采用知识库问答
    knowledge.value = !knowledge.value;
    if (knowledge.value) {
        ElMessage({
            type: "success",
            message: "已开启知识库问答",
            duration: 1500,
        });
        formData.knowledge_base_id = activeKnowledgeBaseId.value;
    } else {
        ElMessage({
            type: "success",
            message: "已关闭知识库问答",
            duration: 1500,
        });
        formData.knowledge_base_id = null;
    }
};
//与子组件直接通信
provide("showDrawer", showDrawer);

// 添加组件卸载时的清理代码
onUnmounted(() => {
    if (scrollbar.value && scrollbar.value.wrap) {
        scrollbar.value.wrap.removeEventListener("scroll", handleScroll);
    }
    if (scrollTimer.value) {
        clearTimeout(scrollTimer.value);
    }
});
</script>

<style lang="scss" scoped>
.pdfContainer {
    min-width: 40vw;
    min-height: 100vh;
    position: fixed;
    right: 0;
    top: 0;
}

.deepThink {
    background-color: #e9f3f2;
    border: 0.6px solid #c3dfdc;
    color: #c3dfdc;
}

.noDeepThink {
    border: 0.6px solid rgba(135, 135, 135, 0.5686);
    color: rgba(135, 135, 135, 0.5686);
}

.useKnowledge {
    background-color: #e9f3f2;
    border: 0.6px solid #c3dfdc;
    color: #c3dfdc;
}

.useKnowledgeText {
    color:#00569D;
}

.noKnowledgeText {
    color: black;
}

.deepThinkText {
    color:#00569D;
}

.noDeepThinkText {
    color: black;
}

.noKnowledge {
    border: 0.6px solid rgba(135, 135, 135, 0.5686);
    color: rgba(135, 135, 135, 0.5686);
}

.index {
    position: fixed;
    top: 0;
    left: 0;
    // min-width: 100vw;
    min-height: 100vh;
    background: url("../../assets/indexBg.png") no-repeat center;
    background-size: cover;
    padding-top: 50px;
    padding-right: 40px;

    .conversationContent {
        margin: 0 auto;
        width: 60%;
        height: 60vh;

        .histroyContent {
            width: 100%;
            padding: 0 10px;

            .userSend {
                display: flex;
                justify-content: flex-end;
                margin-right: 10px;
                margin-top: 20px;

                .userImg {
                    width: 50px;
                    height: 50px;
                    margin-left: 20px;

                    img {
                        width: 100%;
                        height: 100%;
                    }
                }

                .userMsg {
                    background: #e0ecff;
                    border-radius: 10px;
                    padding: 10px;
                }
            }

            .aiSend {
                margin-top: 20px;
                background-color: #fff;
                border-radius: 15px;
                padding-top: 10px;
                padding-bottom: 30px;

                .aiImg {
                    width: 50px;
                    height: 50px;

                    img {
                        width: 100%;
                        height: 100%;
                    }
                }

                .aiReason {
                    border-left: 2px solid #b2b0b0;
                    border-radius: 5px;
                    padding-left: 15px;
                    font-size: 12px;
                    line-height: 26px;
                    color: #3d3d3d;
                    background-color: #f4f3f3;
                }

                .aiContent {
                    margin-top: 10px;
                    padding-left: 30px;
                }

                .aiFile {
                    .line {
                        width: 97%;
                        height: 1px;
                        background: #999999;
                        margin: 10px auto;
                    }

                    .aiFileContent {
                        display: flex;
                        align-items: center;

                        .aiFileName {
                            padding: 0 20px;
                            cursor: pointer;

                            &:hover {
                                color: #4c6fec;
                            }
                        }
                    }
                }
            }
        }

        .sendContent {
            width: 100%;
            padding: 0 10px;

            .userSend {
                display: flex;
                justify-content: flex-end;
                margin-right: 10px;
                margin-top: 20px;

                .userImg {
                    width: 50px;
                    height: 50px;
                    margin-left: 20px;

                    img {
                        width: 100%;
                        height: 100%;
                    }
                }

                .userMsg {
                    background: #e0ecff;
                    border-radius: 10px;
                    padding: 10px;
                }
            }

            .aiSend {
                margin-top: 20px;
                background-color: #fff;
                border-radius: 15px;
                padding-top: 10px;
                padding-bottom: 30px;

                .aiImg {
                    width: 50px;
                    height: 50px;

                    img {
                        width: 100%;
                        height: 100%;
                    }
                }

                .aiReason {
                    border-left: 2px solid #b2b0b0;
                    border-radius: 5px;
                    padding-left: 15px;
                    font-size: 12px;
                    line-height: 26px;
                    color: #3d3d3d;
                    background-color: #f4f3f3;
                }

                .aiContent {
                    margin-top: 10px;
                    padding-left: 30px;
                }

                .aiLoading {
                    display: flex;
                    align-items: center;

                    .aiLoadingText {
                        margin-right: 10px;
                    }
                }
            }
        }
    }

    .center {
        .centerLogo {
            height: 137px;
            width: 348px;
            margin: 0 auto;

            img {
                width: 100%;
                height: 100%;
            }
        }

        .content {
            width: 60%;
            padding-bottom: 20px;
            border-radius: 40px;
            background: #ffffff;
            box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.3);

            .fileBox {
                width: 259px;
                height: 77px;
                border-radius: 10px;
                background: #f8f8f8;
                margin-left: 20px;
                display: flex;
                align-items: center;
                padding-left: 20px;

                .fileImg {
                    width: 35px;
                    height: 41px;
                    margin-right: 20px;

                    img {
                        width: 100%;
                        height: 100%;
                    }
                }

                .fileInfo {
                    .fileName {
                        font-size: 18px;
                    }

                    .fileSize {
                        margin-top: 5px;
                        font-size: 13px;
                        color: #999999;
                    }
                }
            }

            .sendInput {
                margin-left: 20px;

                :deep(.el-input) {
                    width: 88% !important;
                }

                :deep(.el-textarea__inner) {
                    box-shadow: none;
                    resize: none;
                }

                :deep(.el-input__wrapper) {
                    box-shadow: 0 0 0 0;
                    font-size: 20px;
                }

                :deep(.el-input__inner) {
                    font-size: 14px !important;
                }
            }

            .functionBtn {
                padding: 0 40px;
                display: flex;
                align-items: center;
                justify-content: space-between;

                .btnLeft {
                    display: flex;
                    align-items: center;

                    .knowledge {
                        width: 85px;
                        height: 23px;
                        line-height: 23px;
                        text-align: center;
                        border-radius: 10px;
                        font-size: 11px;
                        cursor: pointer;
                        margin-right: 10px;
                    }

                    .think {
                        width: 85px;
                        height: 23px;
                        line-height: 23px;
                        text-align: center;
                        border-radius: 10px;
                        font-size: 11px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        cursor: pointer;

                        .thinkText {
                            margin-left: 3px;
                        }
                    }
                }

                .btnRight {
                    display: flex;
                    align-items: center;
                    justify-content: space-around;
                    width: 160px;

                    .at {
                        cursor: pointer;

                        .icon-Altgo_ {
                            font-size: 30px !important;
                        }
                    }

                    .link {
                        cursor: pointer;

                        .icon-lianjie {
                            font-size: 30px !important;
                        }
                    }

                    .photo {
                        cursor: pointer;

                        .icon-tupian {
                            font-size: 30px !important;
                        }
                    }

                    .send {
                        cursor: pointer;
                        width: 35px;
                        height: 35px;

                        img {
                            width: 100%;
                            height: 100%;
                        }
                    }
                }
            }
        }
    }

    .entryOne {
        width: 835px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 10px auto;

        .entryItem {
            width: 226px;
            height: 49px;
            text-align: center;
            line-height: 49px;
            border-radius: 20px;
            box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(216, 216, 216, 0.8);
            margin: 0 20px;
            cursor: pointer;

            &:hover {
                box-shadow: 0px 8px 20px 0px rgba(0, 0, 0, 0.15);
                transform: translateY(-3px);
                border-color: rgba(180, 180, 180, 0.9);
                background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
            }

            &:active {
                transform: translateY(0);
                box-shadow: 0px 2px 5px 0px rgba(0, 0, 0, 0.1);
            }
        }
    }

    .drawer {
        position: fixed;
        left: 0;
        top: 0;
        width: 300px;
        height: 100vh;
        background: #DEF4F8;
        box-shadow: 4px 0 10px rgba(0, 0, 0, 0.1);
        transform: translateX(-100%);
        transition: transform 0.3s ease-in-out;
        z-index: 1000;

        &.active {
            transform: translateX(0);
        }
    }
}

.hidden-upload {
    display: none;
}

.upload {
    display: inline-block;
    cursor: pointer;
}

.loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
</style>
